/*
 * @Author: Wangjun
 * @Date: 2023-04-06 15:49:08
 * @LastEditTime: 2024-10-21 09:50:36
 * @LastEditors: wangjun haodreams@163.com
 * @Description: 实现白名单黑名单功能
 * @FilePath: \libs\blacklist\namelist.go
 * hnxr
 */
package namelist

import (
	"bufio"
	"os"
	"strings"
)

type Namelist struct {
	list map[string]int
	path string
}

func New(path ...string) *Namelist {
	nl := NewNamelist()
	nl.Setup(path...)
	return nl
}

func (m *Namelist) Setup(path ...string) {
	m.list = make(map[string]int)
	if len(path) > 0 {
		m.path = path[0]
	}
	m.Load(path...)
}

// 新建一个名单列表
func NewNamelist() *Namelist {
	m := new(Namelist)
	m.list = make(map[string]int)
	return m
}

// 是否是空的
func (m *Namelist) IsEmpty() bool {
	return len(m.list) == 0
}

func (m *Namelist) In(names ...string) bool {
	for i := range names {
		_, ok := m.list[names[i]]
		return ok
	}
	return false
}

func (m *Namelist) Set(names ...string) {
	for i := range names {
		m.list[names[i]] = len(m.list)
	}
}

func (m *Namelist) Remove(names ...string) {
	for i := range names {
		delete(m.list, names[i])
	}
}

func (m *Namelist) SetPath(path string) {
	m.path = path
}

func (m *Namelist) Load(path ...string) (err error) {
	if len(path) > 0 && path[0] != "" {
		m.path = path[0]
	}
	if m.path == "" {
		return
	}
	f, err := os.Open(m.path)
	if err != nil {
		return
	}
	defer f.Close()

	list := make(map[string]int)
	buf := bufio.NewReader(f)
	for line, err := buf.ReadString('\n'); err == nil || len(line) > 0; line, err = buf.ReadString('\n') {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		list[line] = 0
	}
	if len(list) > 0 {
		m.list = list
	}
	return
}

func (m *Namelist) Save() (err error) {
	if m.path == "" {
		return
	}
	f, err := os.Create(m.path)
	if err != nil {
		return
	}
	defer f.Close()
	for key := range m.list {
		f.WriteString(key)
		f.WriteString("\n")
	}
	return
}
